﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Soundteller.Phone.Components;
using Ninject;
using Soundteller.Phone.Facade;

namespace Soundteller.Phone
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        #region Components

        private List<Components.IGameComponent> Components;
        private AudioComponent _audioComponent;
        private SoundtellerComponent _SoundtellerComponent;

        [Inject]
        public AudioComponent AudioComponent
        {
            set
            {
                _audioComponent = value;

                if (!Components.Contains(_audioComponent))
                    Components.Add(_audioComponent);
            }
        }

        [Inject]
        public SoundtellerComponent SoundtellerComponent
        {
            set
            {
                _SoundtellerComponent = value;

                if (!Components.Contains(_SoundtellerComponent))
                    Components.Add(_SoundtellerComponent);
            }
        }

        #endregion

        public GamePage()
        {
            InitializeComponent();
            
            // Get the content manager from the application
            contentManager = (System.Windows.Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromSeconds(1 / 60); // TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            SizeChanged += new SizeChangedEventHandler(GamePage_SizeChanged);
            GraphicsContext.GraphicsDevice = SharedGraphicsDeviceManager.Current.GraphicsDevice;
            SharedGraphicsDeviceManager.Current.DeviceCreated += ((sender, e) => GraphicsContext.GraphicsDevice = SharedGraphicsDeviceManager.Current.GraphicsDevice);

            contentManager.RootDirectory = "Content";
            GraphicsContext.Content = contentManager;

            Components = new List<Components.IGameComponent>();
            AudioComponent = GameFactory.CreateAudioComponent();
            SoundtellerComponent = GameFactory.CreateSoundtellerComponent();

            InitializeGameComponents();
        }

        private void GamePage_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            GraphicsContext.WindowWidth = (int)ActualWidth;
            GraphicsContext.WindowHeight = (int)ActualHeight;
        }

        private void InitializeGameComponents()
        {
            foreach (var component in Components)
            {
                component.Initialize();
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here
            GraphicsContext.GraphicsDevice = SharedGraphicsDeviceManager.Current.GraphicsDevice;
            LoadGameComponents();

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        private void LoadGameComponents()
        {
            foreach (var component in Components)
            {
                component.LoadContent();
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            foreach (var component in Components)
            {
                component.Update(new GameTime(e.TotalTime, e.ElapsedTime));
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.White);

            // TODO: Add your drawing code here
            foreach (Components.IDrawableGameComponent component in Components.Where(c => c is Components.IDrawableGameComponent))
            {
                component.Draw(new GameTime(e.TotalTime, e.ElapsedTime));
            }
        }
    }
}